﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using MediaBrowser;
using MediaBrowser.Library;
using Microsoft.MediaCenter.UI;
using Microsoft.MediaCenter;
using MediaBrowser.Code;
using Microsoft.MediaCenter.Hosting;

using Application=MediaBrowser.Application;


namespace Chocolate
{
    public partial class ChocHelper : ModelItem
    {
        private Item _currentItem;
        private int NavCount = 0;
        private MediaCenterEnvironment mce = AddInHost.Current.MediaCenterEnvironment;
        public Item CurrentItem
        {
            get
            {
                return _currentItem;
            }
            set
            {
               
                    _currentItem = value;
                    if (NavCount > 1)
                    {
                        if (ShowOverview)
                            ShowOverview = false;
                        NavCount = 0;
                    }
                    NavCount++;

                    OverviewTimer.Stop();
                    OverviewTimer.Start();
                    FirePropertyChanged("EndTime");
                    FirePropertyChanged("CurrentItem");
                    FirePropertyChanged("GenreString");
                    FirePropertyChanged("PercentWatched");
                    FireMusicChanges();
                    FireGameChanges();
                }
            
        }

        private static string currentPage = "Page";
        public string CurrentPage
        {
            get { return currentPage; }
            set { currentPage = value; }
        }

        public FolderModel CurrentFolder
        {
            get { return Application.CurrentInstance.CurrentFolder; }
        }


        public bool ShowBackdrop
        {
            get
            {
                Application app = Application.CurrentInstance;
                string backdrop = app.CurrentItem.PrimaryBackdropImagePath;
                if (app.Config.ShowBackdrop && !string.IsNullOrEmpty(backdrop) && File.Exists(backdrop))
                {
                    if (CurrentFolder.DisplayPrefs.UseBackdrop.Value && CurrentPage == "Page")
                        return true;
                    if (CurrentPage == "DetailsPage")
                        return true;
                }
                return false;
            }
        }

        public bool ShowFolderBackdrop
        {
            get
            {
                Application app = Application.CurrentInstance;
                MyConfig conf = new MyConfig();
                if (!ShowBackdrop)
                {
                    if (CurrentFolder != null && conf.EnableFolderBackdrop)
                    {
                        string backdrop = CurrentFolder.PrimaryBackdropImagePath;
                        if (!string.IsNullOrEmpty(backdrop) && File.Exists(backdrop))
                        { return true; }
                    }
                }
                return false;
            }
        }

        public bool ShowRootBackground
        {
            get
            {
                Application app = Application.CurrentInstance;
                if (!ShowFolderBackdrop)
                {
                    if (app.Config.ShowRootBackground && !string.IsNullOrEmpty(app.MainBackdrop))
                    { return true; }
                }
                return false;
            }
        }
        public bool ShowThemeBackground
        {
            get
            {
                Application app = Application.CurrentInstance;
                if (!ShowRootBackground)
                {
                    if (app.Config.ShowThemeBackground)
                    { return true; }
                }
                return false;
            }
        }

        private static Image defaultBackdrop;
        public Image DefaultBackdrop
        {
            get { return defaultBackdrop; }
            set { defaultBackdrop = value; }
        }
        private static Image currentBackdrop;
        public Image CurrentBackdrop
        {
            get { return currentBackdrop; }
            set { currentBackdrop = value; }
        }

        public string EndTime
        {
            get
            {
                return calculateEndTime();
            }
        }

        public ChocHelper()
        {
            setupHelper();
        }
       
        public ChocHelper( Item Item)
        {
            CurrentItem = Item;
            setupHelper();
            
        }

        public void setupHelper()
        {
            SelectedIndex = 0;
            Config = new MyConfig();
            ShowOverview = false;
            OverviewTimer.AutoRepeat = false;
            OverviewTimer.Interval = 2000;
            OverviewTimer.Tick += new EventHandler(delegate
            {
                if (CurrentItem.Overview != "" &&
                      ShowOverview != true &&
                      CurrentItem.ItemTypeString != "Season" &&
                      CurrentItem.ItemTypeString != "Album" &&
                      CurrentItem.ItemTypeString != "ArtistAlbum" &&
                      CurrentItem.ItemTypeString != "Folder" &&
                      CurrentItem.ItemTypeString != "MusicFolder")

                    ShowOverview = true;
                NavCount = 0;
            });
            mce.PropertyChanged += new PropertyChangedEventHandler(this.doesMediaExist);
            this.doesMediaExist(this, null);
        }

        public string CurrentTime
        {
            get 
            {
                DateTime dt = DateTime.Now;
                if (Config.Enable24hr)
                    return dt.ToString("HH:mm"); 
                else
                    return dt.ToString("h:mm");
            }
        }

        private string calculateEndTime()
        {
            if (CurrentItem.HasMediaInfo)
            {
                int minutes = CurrentItem.MediaInfo.RunTime;
                DateTime dt = DateTime.Now;
                dt = dt.AddMinutes(minutes);
                if (Config.Enable24hr)
                    return dt.ToString("HH:mm");
                else
                    return dt.ToString("h:mm");
            }
            return "";
        }

        private static bool navigatingForward = true;
        public bool NavigatingForward
        {
            get {return navigatingForward;}
            set 
            {
                navigatingForward = value;
                FirePropertyChanged("NavigatingForward");
            }
        }

        private static bool isMenuOpen = false;
        public bool IsMenuOpen
        { get
        {
            return isMenuOpen;
        }
            set
            {
                isMenuOpen = value;
                FirePropertyChanged("IsMenuOpen");
            }
        }
        private static bool buttonPanelHasFocus = false;
        public bool ButtonPanelHasFocus
        {
            get
            {
                return buttonPanelHasFocus;
            }
            set
            {
                buttonPanelHasFocus = value;
                FirePropertyChanged("ButtonPanelHasFocus");
            }
        }

        public MyConfig Config
        { get; set; }


        public bool _showOverveiew = new bool();
        public bool ShowOverview
        {
            get { return _showOverveiew; }
            set { _showOverveiew = value; FirePropertyChanged("ShowOverview"); }
        }
        
        private Timer OverviewTimer = new Timer();

        public string GetLongDateString(DateTime date)
        {
            if (date.Date == DateTime.Today)
                return "Added Today"; 
            if (date.Date == DateTime.Today.AddDays(-1))
                return "Added Yesterday";
            else 
                return String.Format("Added on {0}",date.ToLongDateString());
        }

        public bool getProperty(string propertyname)
        {
            return ShowOverview;
        }

        
        public string GenreString
        {
            get
            {
                string genrestring = "";
                CurrentItem.Genres.ForEach(item => genrestring += item+", ");
                if(genrestring.Length>0)
                genrestring = genrestring.Substring(0, genrestring.Length - 2);
                return genrestring;
            }
        }
        public int SelectedIndex
        {
            get; set;
        }
        public Rotation getRotation(int Index)
        {
           
            
            int indexDifference = SelectedIndex - Index;
            Rotation rot = new Rotation();

            if (Math.Abs(indexDifference) > 4)
            {
                rot.AngleDegrees = 5 * 12;
                rot.Axis = new Vector3(0f, 1f, 1f);
                if (indexDifference < 0)
                {
                    rot.AngleDegrees = -(rot.AngleDegrees);
                   
                }
            }
            else if(Math.Abs(indexDifference) > 1 )
            {
                rot.AngleDegrees = 0;
                if (indexDifference < 0)
                {
                    rot.AngleDegrees = -(rot.AngleDegrees);
                }
                rot.Axis = new Vector3(0f, 1f, 0f);
            }
            else
            {
                rot.AngleDegrees = 0;
                rot.Axis = new Vector3(0f, 1f, 0f);

            }
            
          
            return rot;
        }
        public Vector3 getScale(int Index)
        {
          

            int indexDifference = SelectedIndex - Index;
            
            indexDifference = Math.Abs(indexDifference);
            float difs = (float)indexDifference;
            
            if(difs > 7)
            {
                return new Vector3(0.2f,0.2f,0.2f);
               
            }
            else
            {
                return new Vector3((((float)(10 - difs)) / 10), (((float)(10 - difs)) / 10), (((float)(10 - difs)) / 10));
                
            }
            //Vector3 v = new Vector3(1f,1f,(((float)(10 - indexDifference)) / 10));
            
        }
        public float getPosition(int Index)
        {

            //int indexDifference = SelectedIndex - Index;

            ////indexDifference = Math.Abs(indexDifference);
            //if (Math.Abs(indexDifference) > 1)
            //{
            //    if(indexDifference < 0)
            //    {
            //        return new Vector3(20,0,0);
            //    }
            //    return new Vector3(-20, 0, 0);
            //}
            //return new Vector3(0,0,0);
            int indexDifference = SelectedIndex - Index;

            //indexDifference = Math.Abs(indexDifference);
            if (Math.Abs(indexDifference) > 1)
            {

                return 60*indexDifference;
            }
            return 0;
        }
        public Inset getMargin(int Index)
        {
           
            int indexDifference = SelectedIndex - Index;

            indexDifference = Math.Abs(indexDifference);
            if(indexDifference > 1)
            {
                return  new Inset(-15,0,-15,0);
            }
            return new Inset(0,0,0,0);

        }

        public string Resolution
        {
            get
            {
                if (CurrentItem.MediaInfo.Width == 0 || CurrentItem.MediaInfo.Height == 0)
                    return "";

                return CurrentItem.MediaInfo.Width.ToString() + "x" + CurrentItem.MediaInfo.Height.ToString();
            }
        }
        public string AudioBitRate
        {
            get
            {
                if (CurrentItem.MediaInfo.AudioBitRate == 0)
                    return "";

                return (CurrentItem.MediaInfo.AudioBitRate / 1000).ToString() + " " + Kernel.Instance.StringData.GetString("KBsStr");
            }

        }
        public string VideoBitRate
        {
            get
            {
                if (CurrentItem.MediaInfo.VideoBitRate == 0)
                    return "";

                return (CurrentItem.MediaInfo.VideoBitRate / 1000).ToString() + " " + Kernel.Instance.StringData.GetString("KBsStr");
            }
        }

        void doesMediaExist(IPropertyObject obj, string text)
        {
            if (mce.MediaExperience != null)
            {
                mce.MediaExperience.Transport.PropertyChanged += new PropertyChangedEventHandler(this.PlayStateChanged);
                this.PlayStateChanged(this, null);
            }
        }

        DateTime lastCall = DateTime.Now;
        void PlayStateChanged(IPropertyObject sender, string property)
        {
            var diff = (DateTime.Now - lastCall).TotalMilliseconds;
            if (diff < 1000 && diff >= 0 && property != "PlayState")
            {
                return;
            }
            lastCall = DateTime.Now;
            FirePropertyChanged("ShowNowPlayingButton");
            FirePropertyChanged("VideoBackdropApplicable");
        }

        public bool VideoBackdropApplicable
        {
            get
            {
                MyConfig conf = new MyConfig();
                if (conf.EnableVideoBackdrop)
                {
                    if (mce.MediaExperience != null && mce.MediaExperience.MediaMetadata != null)
                    {
                        PlayState state = mce.MediaExperience.Transport.PlayState;
                        MediaMetadata media = mce.MediaExperience.MediaMetadata;
                        if (media.ContainsKey("Duration"))
                            return (state == PlayState.Playing);
                    }
                    else if (mce.MediaExperience != null)
                    {
                        PlayState state = mce.MediaExperience.Transport.PlayState;
                        return (state == PlayState.Playing);
                    }
                }
                return false;
            }
        }
        public bool ShowNowPlayingButton
        {
            get
            {
                if (mce.MediaExperience != null)
                {
                    PlayState state = mce.MediaExperience.Transport.PlayState;
                    return (state == PlayState.Playing || state == PlayState.Paused);
                }
                return false;
            }
        }

        public float PercentWatched
        {
            get
            {
                return calculatePercentWatched();
            }

        }

        private float calculatePercentWatched()
        {
            float progress = .0f;

            if (!string.IsNullOrEmpty(CurrentItem.RunningTimeString))
            {
                int runMinutes = int.Parse(CurrentItem.RunningTimeString.Substring(0, CurrentItem.RunningTimeString.IndexOf(' ')));
                int watchedTimeMinsInt = (int)CurrentItem.WatchedTime.TotalMinutes;

                // make sure we have source values so the math doesn't blow up in our face.
                if (runMinutes > 0 && watchedTimeMinsInt > 0)
                {
                    progress = (float)watchedTimeMinsInt / (float)runMinutes;
                }
            }
            return progress;
        }
    }
}
